package gui_serveur;

import java.io.IOException;
import java.awt.*;

import javax.swing.*;

import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.awt.Dimension;
import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import java.awt.image.BufferedImage;
import java.awt.Dimension;
import java.io.IOException;


public class TCP_serveur extends JFrame
{
	private JLabel lbl_etat, lbl_message;
	private JTextField tf_etat, tf_message;
	private JButton calculateB, exitB;

	ServerSocket servSocket;
	Socket s;
	
	
	public TCP_serveur()
	{
		
		setTitle("Appli Serveur");
		Container pane = getContentPane();

		
	    // ajouter un icone
		ImageIcon icone = new ImageIcon("d:/server.png");
		JLabel image = new JLabel(icone);
		pane.add(image);
		// icon de l'appli
	    Image img = Toolkit.getDefaultToolkit().getImage("d:/serveur.png");
	    setIconImage(img);

	    
	    pane.setLayout(null);
	    
	    lbl_etat = new JLabel("Etat:");
		lbl_message = new JLabel("Message:");
		tf_etat = new JTextField("Le serveur attend la connexion d'un client sur le port 8081");
		tf_message = new JTextField("Rien");
		
		
	    pane.add(lbl_etat);
	    pane.add(lbl_message);
	    pane.add(tf_etat);
	    pane.add(tf_message);

	    
	    lbl_etat.setBounds(10 , 10, 50, 20);	
	    lbl_message.setBounds(10 , 30, 80, 20);	
	    tf_etat.setBounds(100 , 10, 350, 20);	
	    tf_message.setBounds(100 , 30, 350, 20);	
		 
	    
		setSize(500, 400);
		// centre la fenetre
		setLocationRelativeTo(null);
		// fermeture de l'appli
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
	    setVisible(true);
		
		try{
			   servSocket = new ServerSocket(8081);//Socket for server
			   Socket fromClientSocket = servSocket.accept();
			System.out.println("Connexion avec : "+fromClientSocket.getInetAddress());

			   tf_etat.setText("Le serveur est reli  un client");
			   PrintWriter pw = new PrintWriter(fromClientSocket.getOutputStream(), true);
			   BufferedReader br = new BufferedReader(new InputStreamReader(fromClientSocket.getInputStream()));
			   String str = br.readLine();
			   tf_message.setText("Rception : " + str);
			   
			   // Get a communication stream associated with the socket
			   OutputStream s1out = fromClientSocket.getOutputStream();
			   DataOutputStream dos = new DataOutputStream (s1out);
			   // Send a string!
			   dos.writeUTF("Vive l't");
			   // Close the connection, but not the server socket
			   dos.close();
			   s1out.close();
			   fromClientSocket.close();
			   
		 }
		 catch(Exception e)
		 {
		 }

	    

	}
	
	public static void main(String[] args) throws IOException
	{
		TCP_serveur appli = new TCP_serveur();
	    
	        
	}


}
